<template>
  <div class="job-detail" v-loading="loading">
    <template v-if="job">
      <div class="detail-header">
        <div class="job-info">
          <h1 class="job-title">{{ job.title }}</h1>
          <div class="job-meta">
            <span class="salary">{{ job.salary }}</span>
            <span class="city">{{ job.city }}</span>
            <span class="experience">{{ job.experience }}</span>
            <span class="education">{{ job.education }}</span>
          </div>
          
          <div class="job-tags">
            <el-tag
              v-for="tag in job.tags"
              :key="tag"
              size="small"
              class="job-tag"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
        
        <div class="action-buttons">
          <el-button
            type="primary"
            size="large"
            @click="handleApply"
          >
            立即投递
          </el-button>
          
          <el-button
            :type="job.isFavorite ? 'danger' : 'default'"
            size="large"
            @click="handleFavorite"
          >
            <el-icon>
              <Star :fill="job.isFavorite" />
            </el-icon>
            {{ job.isFavorite ? '取消收藏' : '收藏职位' }}
          </el-button>
        </div>
      </div>

      <div class="detail-content">
        <div class="content-section">
          <h2 class="section-title">职位描述</h2>
          <div class="section-content description" v-html="job.description"></div>
        </div>

        <div class="content-section">
          <h2 class="section-title">职位要求</h2>
          <div class="section-content requirements" v-html="job.requirements"></div>
        </div>

        <div class="content-section">
          <h2 class="section-title">工作地址</h2>
          <div class="section-content address">
            <div class="address-text">{{ job.address }}</div>
            <div class="map-container">
              <!-- 这里可以集成地图组件 -->
            </div>
          </div>
        </div>
      </div>

      <div class="detail-sidebar">
        <div class="company-card">
          <div class="company-header">
            <el-image
              :src="job.companyLogo"
              :alt="job.companyName"
              class="company-logo"
            >
              <template #error>
                <div class="logo-placeholder">
                  {{ job.companyName.substring(0, 1) }}
                </div>
              </template>
            </el-image>
            
            <div class="company-info">
              <div class="company-name">{{ job.companyName }}</div>
              <div class="company-meta">
                {{ job.companySize }} · {{ job.companyIndustry }}
              </div>
            </div>
          </div>
          
          <div class="company-detail">
            <div class="detail-item">
              <div class="item-label">公司性质</div>
              <div class="item-value">{{ job.companyType }}</div>
            </div>
            
            <div class="detail-item">
              <div class="item-label">融资阶段</div>
              <div class="item-value">{{ job.companyStage }}</div>
            </div>
            
            <div class="detail-item">
              <div class="item-label">公司规模</div>
              <div class="item-value">{{ job.companySize }}</div>
            </div>
            
            <div class="detail-item">
              <div class="item-label">所属行业</div>
              <div class="item-value">{{ job.companyIndustry }}</div>
            </div>
          </div>
          
          <div class="company-action">
            <el-button type="primary" link @click="viewCompany">
              查看公司主页
            </el-button>
          </div>
        </div>

        <div class="recruiter-card">
          <div class="recruiter-header">
            <el-avatar :src="job.recruiterAvatar" class="recruiter-avatar">
              {{ job.recruiterName.substring(0, 1) }}
            </el-avatar>
            
            <div class="recruiter-info">
              <div class="recruiter-name">{{ job.recruiterName }}</div>
              <div class="recruiter-title">{{ job.recruiterTitle }}</div>
            </div>
          </div>
          
          <div class="recruiter-stats">
            <div class="stat-item">
              <div class="stat-value">{{ job.recruiterResponseRate }}%</div>
              <div class="stat-label">回复率</div>
            </div>
            
            <div class="stat-item">
              <div class="stat-value">{{ job.recruiterResponseTime }}</div>
              <div class="stat-label">平均回复时长</div>
            </div>
          </div>
        </div>

        <div class="similar-jobs">
          <h3 class="similar-title">相似职位</h3>
          <div class="similar-list">
            <div
              v-for="item in similarJobs"
              :key="item.id"
              class="similar-item"
              @click="viewJob(item.id)"
            >
              <div class="item-title">{{ item.title }}</div>
              <div class="item-meta">
                <span class="company">{{ item.companyName }}</span>
                <span class="salary">{{ item.salary }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    
    <el-empty
      v-else-if="!loading"
      description="职位不存在或已下线"
    >
      <template #extra>
        <el-button type="primary" @click="goToJobList">
          查看更多职位
        </el-button>
      </template>
    </el-empty>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Star } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 职位数据
const job = ref(null)
const loading = ref(false)
const similarJobs = ref([])

// 获取职位详情
const fetchJobDetail = async () => {
  loading.value = true
  try {
    // 实际应用中应该调用API
    // const response = await jobApi.getJobDetail(route.params.id)
    // job.value = response.data
    
    // 模拟数据
    job.value = {
      id: 1,
      title: '高级前端开发工程师',
      salary: '25-35k·13薪',
      city: '北京',
      experience: '3-5年',
      education: '本科',
      tags: ['React', 'Vue', 'TypeScript'],
      description: `
        <h3>岗位职责：</h3>
        <p>1. 负责公司核心产品的前端开发工作</p>
        <p>2. 参与产品需求分析，技术方案设计</p>
        <p>3. 持续优化前端架构，提升开发效率和产品性能</p>
        <p>4. 参与团队技术标准制定，编写技术文档</p>
      `,
      requirements: `
        <h3>任职要求：</h3>
        <p>1. 本科及以上学历，3年以上前端开发经验</p>
        <p>2. 精通 HTML、CSS、JavaScript，熟悉 ES6+ 特性</p>
        <p>3. 熟练掌握 Vue、React 等主流框架</p>
        <p>4. 有良好的代码风格和编程习惯</p>
      `,
      address: '北京市朝阳区望京SOHO T1 C座',
      companyLogo: '',
      companyName: '字节跳动',
      companyType: '民营企业',
      companyStage: 'D轮及以上',
      companySize: '10000人以上',
      companyIndustry: '互联网',
      recruiterAvatar: '',
      recruiterName: '张先生',
      recruiterTitle: 'HR',
      recruiterResponseRate: 98,
      recruiterResponseTime: '8小时内',
      isFavorite: false
    }
    
    // 模拟相似职位
    similarJobs.value = [
      {
        id: 2,
        title: '资深前端开发工程师',
        companyName: '腾讯科技',
        salary: '30-45k·14薪'
      },
      {
        id: 3,
        title: '前端架构师',
        companyName: '阿里巴巴',
        salary: '40-60k·16薪'
      }
    ]
    
    // 模拟加载延迟
    setTimeout(() => {
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取职位详情失败', error)
    loading.value = false
    ElMessage.error('获取职位详情失败，请稍后再试')
  }
}

// 投递简历
const handleApply = async () => {
  try {
    // 检查用户是否登录
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录后再投递简历')
      router.push({
        path: '/auth/login',
        query: { redirect: route.fullPath }
      })
      return
    }
    
    // 获取用户默认简历
    // const resume = await resumeApi.getDefaultResume()
    // if (!resume) {
    //   ElMessageBox.confirm(
    //     '您还没有创建简历，是否立即创建？',
    //     '提示',
    //     {
    //       confirmButtonText: '创建简历',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }
    //   ).then(() => {
    //     router.push('/resumes/create')
    //   })
    //   return
    // }
    
    // 确认投递
    await ElMessageBox.confirm(
      '确认要投递简历吗？',
      '提示',
      {
        confirmButtonText: '确认投递',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 调用投递API
    // await jobApi.applyJob({
    //   jobId: job.value.id,
    //   resumeId: resume.id
    // })
    
    ElMessage.success('投递成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('投递简历失败', error)
      ElMessage.error('投递失败，请稍后再试')
    }
  }
}

// 收藏/取消收藏
const handleFavorite = async () => {
  try {
    // 检查用户是否登录
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录后再收藏职位')
      router.push({
        path: '/auth/login',
        query: { redirect: route.fullPath }
      })
      return
    }
    
    // 调用收藏/取消收藏API
    // if (!job.value.isFavorite) {
    //   await jobApi.favoriteJob(job.value.id)
    // } else {
    //   await jobApi.unfavoriteJob(job.value.id)
    // }
    
    // 更新本地状态
    job.value.isFavorite = !job.value.isFavorite
    
    ElMessage.success(job.value.isFavorite ? '收藏成功' : '已取消收藏')
  } catch (error) {
    console.error('收藏操作失败', error)
    ElMessage.error('操作失败，请稍后再试')
  }
}

// 查看公司主页
const viewCompany = () => {
  router.push(`/companies/${job.value.companyId}`)
}

// 查看职位详情
const viewJob = (id) => {
  router.push(`/jobs/${id}`)
}

// 返回职位列表
const goToJobList = () => {
  router.push('/jobs')
}

// 初始化
onMounted(() => {
  fetchJobDetail()
})
</script>

<style lang="scss" scoped>
.job-detail {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: var(--spacing-lg);
  
  .detail-header {
    background: #fff;
    border-radius: var(--border-radius-lg);
    padding: var(--spacing-lg);
    margin-bottom: var(--spacing-xl);
    
    .job-info {
      margin-bottom: var(--spacing-lg);
      
      .job-title {
        font-size: var(--font-size-xl);
        font-weight: 600;
        color: var(--text-primary);
        margin: 0 0 var(--spacing-md);
      }
      
      .job-meta {
        display: flex;
        flex-wrap: wrap;
        gap: var(--spacing-md);
        margin-bottom: var(--spacing-md);

        .meta-item {
          display: flex;
          align-items: center;
          gap: var(--spacing-xs);
          color: var(--text-secondary);

          .icon {
            color: var(--color-primary);
          }
        }

        .salary {
          color: var(--color-success);
          font-weight: 500;
        }
      }
      
      .job-tags {
        display: flex;
        flex-wrap: wrap;
        gap: var(--spacing-sm);
      }
    }
    
    .action-buttons {
      display: flex;
      flex-direction: column;
      gap: var(--spacing-md);
    }
  }
  
  .detail-content {
    background: #fff;
    border-radius: var(--border-radius-lg);
    padding: var(--spacing-lg);
    
    .content-section {
      margin-bottom: var(--spacing-xl);
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-title {
        font-size: var(--font-size-lg);
        font-weight: 600;
        color: var(--text-primary);
        margin: 0 0 var(--spacing-md);
      }
      
      .section-content {
        color: var(--text-secondary);
        line-height: var(--line-height-normal);
        white-space: pre-line;

        ul {
          list-style-type: disc;
          padding-left: var(--spacing-xl);
          margin: var(--spacing-sm) 0;
        }
      }
    }
  }
  
  .detail-sidebar {
    .company-card,
    .recruiter-card,
    .similar-jobs {
      background: #fff;
      border-radius: var(--border-radius-lg);
      padding: var(--spacing-lg);
      margin-bottom: var(--spacing-lg);
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    .company-card {
      .company-header {
        display: flex;
        align-items: center;
        margin-bottom: var(--spacing-lg);
        
        .company-logo {
          width: 60px;
          height: 60px;
          border-radius: var(--border-radius-sm);
          margin-right: var(--spacing-md);
          
          .logo-placeholder {
            width: 100%;
            height: 100%;
            background: var(--color-primary);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            font-weight: 600;
          }
        }
        
        .company-info {
          .company-name {
            font-size: var(--font-size-lg);
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 4px;
          }
          
          .company-meta {
            font-size: var(--font-size-sm);
            color: var(--text-secondary);
          }
        }
      }
      
      .company-detail {
        margin-bottom: var(--spacing-lg);
        
        .detail-item {
          display: flex;
          margin-bottom: var(--spacing-sm);
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .item-label {
            width: 80px;
            font-size: var(--font-size-sm);
            color: var(--text-secondary);
          }
          
          .item-value {
            flex-grow: 1;
            font-size: var(--font-size-sm);
            color: var(--text-primary);
          }
        }
      }
      
      .company-action {
        text-align: center;
      }
    }
    
    .recruiter-card {
      .recruiter-header {
        display: flex;
        align-items: center;
        margin-bottom: var(--spacing-lg);
        
        .recruiter-avatar {
          margin-right: var(--spacing-md);
        }
        
        .recruiter-info {
          .recruiter-name {
            font-size: var(--font-size-lg);
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 4px;
          }
          
          .recruiter-title {
            font-size: var(--font-size-sm);
            color: var(--text-secondary);
          }
        }
      }
      
      .recruiter-stats {
        display: flex;
        justify-content: space-around;
        
        .stat-item {
          text-align: center;
          
          .stat-value {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--color-primary);
            margin-bottom: 4px;
          }
          
          .stat-label {
            font-size: var(--font-size-sm);
            color: var(--text-secondary);
          }
        }
      }
    }
    
    .similar-jobs {
      .similar-title {
        font-size: var(--font-size-lg);
        font-weight: 600;
        color: var(--text-primary);
        margin: 0 0 var(--spacing-md);
      }
      
      .similar-list {
        .similar-item {
          padding: var(--spacing-md);
          border-radius: var(--border-radius-sm);
          cursor: pointer;
          transition: all 0.3s;
          
          &:hover {
            background: var(--bg-light);
          }
          
          .item-title {
            font-size: var(--font-size-lg);
            color: var(--text-primary);
            margin-bottom: 4px;
            @include text-ellipsis;
          }
          
          .item-meta {
            font-size: var(--font-size-sm);
            
            .company {
              color: var(--text-secondary);
              margin-right: var(--spacing-sm);
            }
            
            .salary {
              color: var(--color-success);
            }
          }
        }
      }
    }
  }
}

// 响应式适配
@media (max-width: 1200px) {
  .job-detail {
    grid-template-columns: 1fr;
    
    .detail-sidebar {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: var(--spacing-lg);
      
      .company-card,
      .recruiter-card,
      .similar-jobs {
        margin-bottom: 0;
      }
    }
  }
}

@media (max-width: 768px) {
  .job-detail {
    .detail-header {
      grid-template-columns: 1fr;
      gap: var(--spacing-md);

      .action-buttons {
        flex-direction: row;
        flex-wrap: wrap;

        .el-button {
          flex: 1;
          min-width: 120px;
        }
      }
    }
    
    .detail-sidebar {
      grid-template-columns: 1fr;
    }
  }
}
</style> 